<script lang="ts" setup>
import CellComp from '@/components/CellComp.vue'
import { ref } from 'vue'
import { useUserInfoStore } from '@/stores/userInfo';
import { showConfirmDialog, showFailToast, showLoadingToast, showToast } from 'vant';
import { RequestAxios } from '@/utils/axios';
import b64ToBlob from 'b64-to-blob'
import axios from 'axios';

interface ISelect {
    selectedIndexes: number[],
    selectedOptions: object[],
    selectedValues: string[]

}

const isShowSex = ref(false)
const isShowBirth = ref(false)
const isShowNickname = ref(false)
const isShowIntro = ref(false)
const isShowAvatar = ref(false)
const currentDate = ref(['2024', '12', '02'])
const nickName = ref('')
const intro = ref('')
const gender = ref('0')
const birth = ref('2024-12-05')
const store = useUserInfoStore()
nickName.value = store.userInfo.name
intro.value = store.userInfo.intro
gender.value = store.userInfo.gender
birth.value = store.userInfo.birthday

const onSelect = async (item: IName) => {
    isShowSex.value = false
    store.userInfo.gender = item.name === '男' ? '0' : '1'
    await RequestAxios<IRes>({
        url: 'v1_0/user/profile',
        method: 'patch',
        data: {gender: store.userInfo.gender}
    })

    gender.value = store.userInfo.gender
    jk.updateUserInfo(store.userInfo)
}
const onAvatarSelect = async (item: IName) => {
    if(item.name === '拍照') {
        const b64Str = await jk.getCameraStr()
        uploadImg(b64Str)
    }
    else {
        const b64Str = await jk.getPhotoStr()
        uploadImg(b64Str)
    }
}
const uploadImg = async (str: string) => {
    const file = b64ToBlob(str, 'image/jpeg')

  const fd = new FormData()
  fd.append('photo', file, Date.now() + '.jpeg')


  showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
  const res = await axios.patch('https://geek.itheima.net/v1_0/user/photo', fd, {
        headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': 'Bearer ' + store.token
        }
      })
  store.userInfo.photo = res.data.data.photo
  jk.updateUserInfo(store.userInfo)

  showToast('上传成功')
}

const changeNickName = () => {
    isShowNickname.value = true
    jk.changeNavBar('nickName')
}

const changeIntro = () => {
    isShowIntro.value =true
    jk.changeNavBar('intro')
}

const closeFn = () => {  // 通过鸿蒙调用取消Popup的展示
    isShowNickname.value = false
    isShowIntro.value = false
    jk.resetNavBar()
}
jk.closeFunc(closeFn)

const confirmBirth = async (val: ISelect) => {
    isShowBirth.value = false
    const birthday = val.selectedValues.join('-')
    await RequestAxios<IRes>({
        url: 'v1_0/user/profile',
        method: 'patch',
        data: {birthday: birthday}
    })
    store.userInfo.birthday = birthday
    birth.value = birthday
    jk.updateUserInfo(store.userInfo)
}

const submitNickName = async () => {
    isShowNickname.value = false
    await RequestAxios<IRes>({
        url: 'v1_0/user/profile',
        method: 'patch',
        data: {name: store.userInfo.name}
    })
    nickName.value = store.userInfo.name

    jk.updateUserInfo(store.userInfo)
    showFailToast("更新成功")
}
jk.submitNickNameFunc(submitNickName)
const submitIntro = async () => {
    isShowIntro.value = false
    await RequestAxios<IRes>({
        url: 'v1_0/user/profile',
        method: 'patch',
        data: {intro: store.userInfo.intro}
    })    
    intro.value = store.userInfo.intro
    showFailToast("更新成功")
    jk.updateUserInfo(store.userInfo)
}
jk.submitIntroFunc(submitIntro)

const logout = () => {
    showConfirmDialog({
        title: '温馨提示',
        message: '亲，您确定要退出登录吗？',
        confirmButtonText: '取消',
        showCancelButton: true,
        confirmButtonColor: '#ccc',
        cancelButtonColor: '#EE0A24',
        cancelButtonText: '确认'
    }).then(() => {
        console.log("用户取消了退出登录")
    })
    .catch(() => {
        jk.logout()
    })
}

const actions = [
      { name: '男' },
      { name: '女' }
    ];

const avatarActions = [
    { name: '拍照' },
    { name: "选择照片" }
]
console.log(store.token)
</script>

<template>
  <div class="container">
    <CellComp title="头像" :src="store.userInfo.photo" @click="isShowAvatar=true" :is-img="true" />
    <CellComp title="昵称" :text-val="nickName" :is-img="false" @click="changeNickName" />
    <CellComp title="简介" :text-val="intro" @click="changeIntro" :is-img="false" />
    <div class="box-margin"></div>
    <CellComp title="性别" :text-val="gender == '1' ? '女' : '男'" :is-img="false" @click="isShowSex = true" />
    <CellComp title="生日" @click="isShowBirth=true" :text-val="birth" :is-img="false" />
    <div class="logout">
        <p class="logoutBtn" @click="logout">退出登录</p>
    </div>
    <van-action-sheet v-model:show="isShowSex" :actions="actions" close-on-click-action cancel-text="取消" @select="onSelect" />
    <van-action-sheet v-model:show="isShowAvatar" :actions="avatarActions" close-on-click-action cancel-text="取消" @select="onAvatarSelect" />
    <van-popup v-model:show="isShowBirth" position="bottom">
        <van-date-picker
            v-model="currentDate"
            title="选择年月日"
            :min-date="new Date('1900-01-01')"
            :max-date="new Date()"
            @cancel="isShowBirth=false"
            @confirm="confirmBirth"
        >
        <template #confirm>
            <span class="confirm">确定</span>
        </template>
    </van-date-picker>
    </van-popup>
    <van-popup 
        style="width: 100%"
        v-model:show="isShowNickname"
        position="right"
    >
        <div class="content">
            <h2 class="title">昵称</h2>
            <div class="boxField">
                <van-field v-model="store.userInfo.name" placeholder="请输入昵称" />
            </div>
        </div>
    </van-popup>
    <van-popup
        style="width: 100%"
        v-model:show="isShowIntro"
        position="right"
    >
        <div class="content">
            <h2 class="title">简介</h2>
            <div class="boxField">
                <van-field
                    v-model="store.userInfo.intro"
                    rows="2"
                    autosize
                    type="textarea"
                    maxlength="50"
                    placeholder="请输入"
                    show-word-limit
                />
            </div>
        </div>
    </van-popup>
    <van-dialog show-cancel-button>
    </van-dialog>
  </div>
</template>

<style scoped>
    .container {
        width: 100%;
        height: 100%;
        background-color: #F7F8FA;
    }
    .box-margin {
        margin-bottom: 12px;
    }
    .confirm {
        color: #FC6728;
    }
    .content {
        display: flex;
        flex-direction: column;
        height: 100vh;
        width: 100vw;
        background-color: #F7F8FA;
    }
    .title {
        font-size: 17px;
        margin: 15px 0 15px 16px;
    }
    .boxField {
        padding: 0 16px;
    }
    .logout {
        width: calc(100% - 32px);
        height: 44px;
        padding: 0 16px;
        position: absolute;
        bottom: 60px;
    }
    .logoutBtn {
        height: 44px;
        background-color: #FC6728;
        text-align: center;
        color: #fff;
        line-height: 44px;
        border-radius: 6px;
    }
    .tips {
        text-align: center;
        color: #ccc;
    }
</style>